package com.smat.taglib;

import com.smat.taglib.html.Div;
import com.smat.taglib.html.Element;
import com.smat.taglib.html.Script;
import com.smat.taglib.json.Serializable;
import com.smat.taglib.json.Serializer;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.DynamicAttributes;

public abstract class WidgetTag extends BaseTag
  implements Serializable, DynamicAttributes
{
  private String name;
  private String widget;
  protected Map<String, Object> attributes;

  public WidgetTag(String widget)
  {
    this.widget = widget;
  }

  public String getName() {
    return this.name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public void initialize() {
    this.attributes = new HashMap();

    super.initialize();
  }

  public void destroy()
  {
    this.attributes = null;

    super.destroy();
  }

  public void setDynamicAttribute(String uri, String localName, Object value) throws JspException
  {
    this.attributes.put(localName, value);
  }

  public int doEndTag() throws JspException
  {
    JspWriter out = this.pageContext.getOut();

    Element element = html();
    Script script = script();
    try
    {
      element.write(out);

      script.write(out);
    } catch (IOException exception) {
      throw new JspException(exception);
    }

    return super.doEndTag();
  }

  public Element<?> html() {
    Element element = createElement();

    element.attr("id", getName());

    for (String attribute : this.attributes.keySet()) {
      Object value = this.attributes.get(attribute);

      if (value != null) {
        element.attr(attribute, value);
      }
    }

    return element;
  }

  public Script script() {
    StringWriter content = new StringWriter();

    content.append("jQuery(function(){jQuery(\"#").append(getName()).append("\").kendo").append(this.widget).append("(");
    try
    {
      new Serializer().serialize(content, this);
    }
    catch (IOException exception)
    {
    }
    content.append(");})");

    Script script = new Script();

    script.html(content.toString());

    return script;
  }

  protected Element<?> createElement() {
    return new Div();
  }
}